//
//  HelperListVC.swift
//  d11
//
//  Created by peale on 2019/1/23.
//  Copyright © 2019年 Tech_001. All rights reserved.
//

import UIKit

class HelperListVC: BXBaseVC,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    var navigationRightButton: UIButton?
    var listData:[[String:Any]]?
    
    lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        if kIsIpad == true{
            layout.itemSize = CGSize(width: (kScreenWidth-13-120)/7, height: ((kScreenWidth-13-120)/7)+45)
            layout.sectionInset = UIEdgeInsets.init(top: 20, left: 15, bottom: 0, right: 15)
            layout.minimumInteritemSpacing = 30
        }else{
            if kScreenWidth<=320{
                layout.itemSize = CGSize(width: (kScreenWidth-13-80)/4, height: ((kScreenWidth-13-80)/4)+45)
                layout.sectionInset = UIEdgeInsets.init(top: 20, left: 10, bottom: 0, right: 10)
                layout.minimumInteritemSpacing = 20
            }else{
                layout.itemSize = CGSize(width: (kScreenWidth-13-120)/4, height: ((kScreenWidth-13-120)/4)+45)
                layout.sectionInset = UIEdgeInsets.init(top: 20, left: 15, bottom: 0, right: 15)
                layout.minimumInteritemSpacing = 30
            }
        }
      
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .vertical
        
        let collView = UICollectionView.init(frame: CGRect(x:13, y:kNavigationBarHeight, width:kScreenWidth-13, height:kScreenHeight-kNavigationBarHeight), collectionViewLayout: layout)

        if collView.responds(to:#selector(setter: UIView.layoutMargins)) {
            collView.layoutMargins = .zero;
        }
        
        collView.autoresizingMask = UIView.AutoresizingMask.flexibleWidth.union(UIView.AutoresizingMask.flexibleHeight)
        collView.register(HelperListCell.self, forCellWithReuseIdentifier: "HelperListCell")
        collView.register(HelperListHeadView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HelperListHeadView1")
        collView.showsVerticalScrollIndicator = false
        collView.showsHorizontalScrollIndicator = false
        collView.backgroundColor = UIColor.white
        collView.delegate = self
        collView.dataSource = self
        
        collView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.pullToRefresh()
        })
        collView.mj_header?.backgroundColor = UIColor.init("f5f5f5")
        return collView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航栏右边按钮
        configureNavigationRightButton()
        //设置导航栏图片标题
        navigationItemTitleView()
        notificationCenterListener()
        if GlobalInfo.helperList == nil{
            listData = []
        }else{
            listData = GlobalInfo.helperList
        }
        self.view.backgroundColor = HexRGBAlpha(0xF8F9FB, 1)
        
        self.view.addSubview(self.collectionView)
        
        self.pullToRefresh()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationRightButton?.isHidden = UserHelper.getLoginStatus()
        self.navigationBarClear()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationBarDefault()
        self.navigationRightButton?.isHidden = true
    }
    func notificationCenterListener() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.userLoginSucceed), name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_SUCCEED), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.userLoginOut), name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_OUT), object: nil)
    }
    
    @objc func userLoginSucceed() {
        DispatchQueue.main.async {
            self.navigationRightButton?.isHidden = true
        }
    }
    @objc func userLoginOut() {
        DispatchQueue.main.async {
            self.navigationRightButton?.isHidden = false
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_SUCCEED), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: DefaultKey.USER_LOGIN_OUT), object: nil)
    }
    // 配置顶部登录按钮
    func configureNavigationRightButton() {
        // 登录按钮
        self.navigationRightButton = UIButton.init(frame: CGRect(x: self.view.frame.width - 54, y: 0, width: 54, height: 28))
        // 渐变色
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.navigationRightButton!.bounds
        gradientLayer.colors = [
            UIColor.init("FBCE81")!.cgColor,
            UIColor.init("FF914A")!.cgColor
        ]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0)
        self.navigationRightButton!.layer.insertSublayer(gradientLayer, at: 0)
        self.navigationRightButton!.clipRectCorner(direction: [UIRectCorner.topLeft,UIRectCorner.bottomLeft], cornerRadius: 14)
        self.navigationRightButton!.setTitle("  登录", for: UIControl.State.normal)
        self.navigationRightButton!.setTitleColor(UIColor.white, for: UIControl.State.normal)
        self.navigationRightButton!.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
        self.navigationRightButton!.addTarget(self, action: #selector(navigationRightButtonClick), for: UIControl.Event.touchUpInside)
        self.navigationController?.navigationBar.addSubview(self.navigationRightButton!)
        self.navigationRightButton!.snp.makeConstraints { (make) in
            make.centerY.right.equalToSuperview()
            make.width.equalTo(54)
            make.height.equalTo(28)
        }
    }
    
    
    @objc func navigationRightButtonClick(){
        LoginViewController.loginIfNeedController(currentController: self) {
            
            print("登录成功")
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return listData?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let dict:[String:Any] = listData?[section] ?? [:]
        let fList:[[String:Any]] =  dict["funcation_data"] as? [[String : Any]] ?? []
        return fList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        if section == 0 {
            return CGSize.init(width: kScreenWidth-13, height: 44)
        }
        
        return CGSize.init(width: kScreenWidth-13, height: 64)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var reusableview:HelperListHeadView!
        
        if kind == UICollectionView.elementKindSectionHeader {
            
            reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HelperListHeadView1", for: indexPath) as? HelperListHeadView
            let dict:[String:Any] = listData?[indexPath.section] ?? [:]
            reusableview.setData(title:  dict["head_title"] as? String ?? "")
        }
        return reusableview
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.init(width: 0, height: 0)
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:HelperListCell = collectionView.dequeueReusableCell(withReuseIdentifier: "HelperListCell", for: indexPath) as! HelperListCell
        let dict:[String:Any] = listData?[indexPath.section] ?? [:]
        let fList:[[String:Any]] =  dict["funcation_data"] as? [[String : Any]] ?? []
        cell.setData(dict: fList[indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let dict:[String:Any] = listData?[indexPath.section] ?? [:]
        let fList:[[String:Any]] =  dict["funcation_data"] as? [[String : Any]] ?? []
        let dataDict:[String:Any] = fList[indexPath.row]
        let url = dataDict["url"] as? String ?? ""
        let title = dataDict["title"] as? String
        //这里加权限
        if dict["type"] !=  nil{
            // Skip helper app
        }else{
            let goNext: WebViewController = WebViewController.init()
            if(title=="体育直播"){
                goNext.url = url.replacingOccurrences(of: "https", with: "http")
                print("路径\(url)")
                goNext.hidesBottomBarWhenPushed = true
                let urlComponents = NSURLComponents(string: goNext.url ?? "")
                let queryItems =  urlComponents?.queryItems
                var isCatch = true
                if queryItems != nil && queryItems?.count ?? 0 > 0{
                    for item in queryItems!{
                        if item.name == "catch"{
                            if item.value == "false" {
                                isCatch = false
                            }
                            break
                        }
                    }
                }
                goNext.isHelper = isCatch
                self.navigationController?.pushViewController(goNext, animated: true)
            }else{
                
                if title == "亚运专栏"{
                    goNext.isLoadjsCode = true
                }
                print("路径\(url)")
                goNext.url = url
                goNext.hidesBottomBarWhenPushed = true
                let urlComponents = NSURLComponents(string: goNext.url ?? "")
                let queryItems =  urlComponents?.queryItems
                var isCatch = true
                if queryItems != nil && queryItems?.count ?? 0 > 0{
                    for item in queryItems!{
                        if item.name == "catch"{
                            if item.value == "false" {
                                isCatch = false
                            }
                            break
                        }
                    }
                }
                goNext.isHelper = isCatch
                self.navigationController?.pushViewController(goNext, animated: true)
            }
        }
    }
 
    func pullToRefresh(){
        RequestHelper.get(GlobalInfo.resDomain, atPath: "/game_new.json", withCompletion: { data in
            let gameInfoArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            //GlobalInfo.helperInfoData = gameInfoArray["helper"] as? [[String:Any]]
            print("数据\(gameInfoArray)")
            GlobalInfo.gameInfoData = gameInfoArray
            GlobalInfo.helperList = gameInfoArray["helper_List"] as? [[String:Any]]
            if GlobalInfo.helperList == nil{
                self.listData = []
            }else{
                self.listData = GlobalInfo.helperList
            }
            DispatchQueue.main.async {
                self.collectionView.reloadData()
                self.collectionView.mj_header?.endRefreshing()
            }
            
        }, withError: { error in
            DispatchQueue.main.async {
                self.collectionView.mj_header?.endRefreshing()
                UIHelper.alertSimpleMessage(about: "无法获取配置文件信息，请联系客服\(getErrorString())", withDescription: "", in: self)
            }
        })
    }
}
